package com.mx.web.service;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.mx.web.model.User;

@Service
public class UserService implements UserDetailsService{
	
	@Autowired
	private MongoTemplate mongoTemplate;

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	  
	public User register(User user) {
		logger.info("执行UserService.register()方法");
		mongoTemplate.save(user);
		return user;
	}
	
	public User signin(User user) {
		logger.info("执行UserService.signin()方法");
		
		Query query = query(
				where("userName").is(user.getUsername())
				.and("password").is(user.getPassword())
			);
		user = mongoTemplate.findOne(query, User.class);
		return user;
	}

	public User getByUsername(String username) {
		logger.info("执行UserService.getByUsername()方法");
		Query query = query( where("username").is(username) );
		logger.info(""+query);
		logger.info(""+mongoTemplate);
		User u = mongoTemplate.findOne(query, User.class);
		logger.info("User: {} {}", u.getUsername(), u.getPassword());
		return u;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("用户名是{}",username);
		User user = this.getByUsername(username);
		logger.info("密码是{}",user.getPassword());
		logger.info("Username:({})",user.getUsername());
		
		return new org.springframework.security.core.userdetails.User(username, user.getPassword(), user.getAuthorities());
	}
}